#include "./RulerWidget.h"
namespace qbe::canvas {

RulerWidget::RulerWidget(QWidget* parent) : QWidget(parent) {}
RulerWidget::RulerWidget(QString name, int width, int height, QWidget* parent) : QWidget(parent), name(name), width(width), height(height) {

  this->setStyleSheet("background-color:yellow;");
  // ruler_y_widget->setStyleSheet("background-color:yellow;");
  if (name == QString::fromLocal8Bit("x")) {
    this->setFixedHeight(height);
    // this->setMinimumHeight(height);
    // this->setMaximumHeight(height);
  }
  if (name == QString::fromLocal8Bit("y")) {
    this->setFixedWidth(width);
    // this->setMinimumWidth(width);
    // this->setMaximumWidth(width);
  }

  // signalRulerLines(axis.rulerX.paths, axis.rulerY.paths, QVector2D(axis.mouse_pixel_x, axis.mouse_pixel_y));
  // ServiceEvent::getInstance()->myRegisterFunc<void(qlib::Cell::s_ptr)>("Board/RulerUpdate", &CellGroup::showCell_ecs, this, std::placeholders::_1);
}

RulerWidget::~RulerWidget() {}

void RulerWidget::paintEvent(QPaintEvent* event) {
  QPainter painter(this);
  // 抗锯齿
  painter.setRenderHint(QPainter::Antialiasing);
  // painter.fillRect(this->rect(), QColor(255, 222, 173));

  QPen pen = QPen(Qt::black, 1);
  QPen pen_red = QPen(Qt::red, 1);
  QPen pen_green = QPen(Qt::green, 1);
  QFont font = QFont("宋体", 12);  // 字体设置

  painter.setFont(font);  // painter设置字体
  if (name == QString::fromLocal8Bit("x")) {
    // 实时位置
    painter.setPen(pen_red);
    painter.drawLine(QLineF(m_pos[0], 10, m_pos[0], height));
    for (int i = 0; i < m_lines_x.length(); i++) {
      QVector<double> v = m_lines_x[i];
      painter.setPen(pen);  // painter设置画笔
      painter.drawLine(QLineF(v[0], v[1], v[2], v[3]));
      if (v.length() == 8) {
        painter.setPen(pen_red);  // painter设置画笔
        painter.drawText(v[5], v[6], QString::asprintf("%.3f", v[7]));
      }
    }
  }

  if (name == QString::fromLocal8Bit("y")) {
    // 实时位置
    painter.setPen(pen_red);
    painter.drawLine(QLineF(10, m_pos[1], width, m_pos[1]));
    for (int i = 0; i < m_lines_y.length(); i++) {
      QVector<double> v = m_lines_y[i];
      painter.setPen(pen);  // painter设置画笔
      painter.drawLine(QLineF(v[0], v[1], v[2], v[3]));
      if (v.length() == 8) {
        painter.setPen(pen_red);  // painter设置画笔
        // 采用平移坐标位置，旋转，重置矩阵
        painter.translate(v[5], v[6]);
        painter.rotate(-90);
        painter.drawText(1, 1, QString::asprintf("%.3f", v[7]));
        painter.resetTransform();
      }
    }
  }
}

void RulerWidget::onDraw(const QList<QVector<double>>& lines_x, const QList<QVector<double>>& lines_y, const QVector2D& pos) {
  m_lines_x = lines_x;
  m_lines_y = lines_y;
  m_pos = pos;

  this->update();
}

}  // namespace qbe::canvas